package com.mjf.io.output;

import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;

/**
 * FileWriter:字符输出流
 *  注意：写完文件以后一定要调用 FileWriter.flush() 或者 FileWriter.close() 方法将数据从内存刷到磁盘，否则数据会丢失！！！
 */
public class FileWriterUse {

    /**
     * new FileWriter(outputPath):覆盖写入
     */
    @Test
    public void fileWrite01() {
        String outputPath = "D:\\coding\\idea\\java-stu\\output\\hello2.txt";
        FileWriter fw = null;
        try {
            fw = new FileWriter(outputPath);
            fw.write(67);   // 写入单个字符
            fw.write(new char[]{'a', 'b', 'c'});    // 写入字符数组
            fw.write("hello");  // 写入字符串
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fw != null) {
                    fw.flush();
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * new FileWriter(outputPath, true):追加写入
     */
    @Test
    public void fileWrite02() {
        String outputPath = "D:\\coding\\idea\\java-stu\\output\\hello2.txt";
        FileWriter fw = null;
        try {
            fw = new FileWriter(outputPath, true);
            fw.write(new char[]{'\n', 'b', 'c'});    // 写入字符数组
            fw.write(67);   // 写入单个字符
            fw.write("hello");  // 写入字符串
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
